package cn.hty.mymsg.handler.receiver.service.impl;

import cn.hty.mymsg.common.domain.AnchorInfo;
import cn.hty.mymsg.common.domain.LogParam;
import cn.hty.mymsg.common.domain.RecallTaskInfo;
import cn.hty.mymsg.common.domain.TaskInfo;
import cn.hty.mymsg.common.enums.AnchorState;
import cn.hty.mymsg.handler.handler.HandlerHolder;
import cn.hty.mymsg.handler.pending.Task;
import cn.hty.mymsg.handler.pending.TaskPendingHolder;
import cn.hty.mymsg.handler.receiver.service.ConsumeService;
import cn.hty.mymsg.handler.uitls.GroupIdMappingUtils;
import cn.hty.mymsg.utils.LogUtils;
import cn.hutool.core.collection.CollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class ConsumeServiceImpl implements ConsumeService {

    private static final String LOG_BIZ_TYPE = "Receiver#consumer";
    private static final String LOG_BIZ_RECALL_TYPE = "Receiver#recall";
    @Autowired
    private ApplicationContext context;

    @Autowired
    private TaskPendingHolder taskPendingHolder;

    @Autowired
    private LogUtils logUtils;


    @Override
    public void consume2Send(List<TaskInfo> taskInfoLists) {
        //获取模板列表的第一个groupId
        String topicGroupId = GroupIdMappingUtils.getGroupIdByTaskInfo(CollUtil.getFirst(taskInfoLists.iterator()));
        //遍历模板列表，分配到线程执行
        for (TaskInfo taskInfo : taskInfoLists) {
            logUtils.print(LogParam.builder().bizType(LOG_BIZ_TYPE).object(taskInfo).build(),
                    AnchorInfo.builder().bizId(taskInfo.getBizId()).messageId(taskInfo.getMessageId())
                            .ids(taskInfo.getReceiver()).businessId(taskInfo.getBusinessId())
                            .state(AnchorState.RECEIVE.getCode()).build());
            Task task = context.getBean(Task.class).setTaskInfo(taskInfo);
            taskPendingHolder.route(topicGroupId).execute(task);
        }
    }
}
